package com.fqcar.fqdf.ui;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.widget.AppCompatEditText;
import android.support.v7.widget.AppCompatTextView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;

import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
import com.alibaba.sdk.android.oss.callback.OSSProgressCallback;
import com.alibaba.sdk.android.oss.internal.OSSAsyncTask;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.android.volley.Response;
import com.baidu.location.BDLocation;
import com.fqcar.fqdf.DFApp;
import com.fqcar.fqdf.R;
import com.fqcar.fqdf.adapter.EndDealWithProblemsImageAdapter;
import com.fqcar.fqdf.adapter.EndDealWithProblemsReasonAdapter;
import com.fqcar.fqdf.core.base.BasePhotoActivity;
import com.fqcar.fqdf.entity.CarPhotoBean;
import com.fqcar.fqdf.entity.StartDealRespBean;
import com.fqcar.fqdf.service.RequestOptService;
import com.fqcar.fqdf.util.StorageUtil;
import com.jph.takephoto.model.TResult;
import com.fqdf.framework.android.net.response.NetBaseWrapper;
import com.fqdf.framework.android.net.response.NetBeanWrapper;
import com.fqdf.framework.android.util.CheckLogicUtil;
import com.fqdf.framework.android.util.Constants;
import com.fqdf.framework.android.util.DialogUtil;
import com.fqdf.framework.android.util.FileUtil;
import com.fqdf.framework.android.view.NoScrollGridLayoutManager;
import com.fqdf.framework.android.view.listener.RecycleItemClickListener;
import com.fqdf.framework.android.view.recycleviewdivider.GridSpacingDecoration;
import com.fqdf.framework.android.view.recycleviewdivider.HorizontalLineSpacingDecoration;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @author lvsidong
 * @version V1.0
 * @date 2017/10/17
 */
public class EndDealWithProblemsActivity extends BasePhotoActivity implements RecycleItemClickListener, BasePhotoActivity.PickAndCameraListener {


    @BindView(R.id.cancel_reason)
    RecyclerView cancelReason;
    @BindView(R.id.cancel_img)
    RecyclerView cancelImg;
    @BindView(R.id.uoload_img_txt)
    AppCompatTextView uoloadImgTxt;
    @BindView(R.id.input_reason_edit)
    AppCompatEditText inputReasonEdit;
    @BindView(R.id.confirm)
    Button confirm;

    private int curClickPosition;
    private BDLocation location = null;
    private List<String> reasonList = new ArrayList<>();

    private EndDealWithProblemsImageAdapter uploadImgAdapter;

    private EndDealWithProblemsReasonAdapter reasonAdapter;
    private int carId;

/*
    private interface ButtonClickListener{
        void setBackground();
    }*/

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_end_deal_with_problems_reason);
        ButterKnife.bind(this);

        carId = getIntent().getIntExtra(Constants.BUNDLE_DATA,0);
        location = ((DFApp)getApplication()).getCurLocation();
        getReasonList();
        initMyView();
    }

    /**
     * 初始化View
     */
    private void initMyView() {
        initRecycleView();
        inputReasonEdit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if(editable.length() > 0){
                    confirm.setEnabled(true);
                    confirm.setBackgroundResource(R.drawable.btn_main_new_darkgreen);
                }else {
                    confirm.setEnabled(false);
                    confirm.setBackgroundResource(R.drawable.btn_cancel_order_confirm);
                }
            }
        });
    }

    /**
     * 初始化recycleview控件以及数据
     */
    private void initRecycleView() {

        NoScrollGridLayoutManager gridManager = new NoScrollGridLayoutManager(this, 2);
        cancelReason.setLayoutManager(gridManager);

        reasonAdapter = new EndDealWithProblemsReasonAdapter(reasonList,this);
        cancelReason.setAdapter(reasonAdapter);
        cancelReason.addItemDecoration(new GridSpacingDecoration(getResources().getDimensionPixelOffset(R.dimen.dimen_15_dip),
                getResources().getDimensionPixelOffset(R.dimen.dimen_12_dip), false));


        LinearLayoutManager linearManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);

        uploadImgAdapter = new EndDealWithProblemsImageAdapter(this, 6, uoloadImgTxt);
        cancelImg.setLayoutManager(linearManager);
        cancelImg.setAdapter(uploadImgAdapter);
        cancelImg.addItemDecoration(new HorizontalLineSpacingDecoration(getResources().getDimensionPixelOffset(R.dimen.dimen_17_dip)));

    }

    /**
     * 进行拍照
     *
     * @param position 当前点击的view position
     */
    private void startCamera(int position) {
        curClickPosition = position;
        File cache = StorageUtil.getTakePhotoDir(this);
        File desFile = new File(cache, StorageUtil.generateFileName());
        getTakePhoto().onPickFromCapture(Uri.fromFile(desFile));
    }

    @Override
    public void takeSuccess(TResult result) {
        getUploadImgProgressDialog().show();
        String filePath = result.getImage().getCompressPath();
//        uploadFile(filePath, curClickPosition);
        uploadImage(filePath, curClickPosition);
    }

    @Override
    public void onItemClick(View view, int position) {
//        new PickAndCameraPhotoDialog(EndDealWithProblemsActivity.this).show();
        onClickTakePhoto();
        curClickPosition = position;
    }

    @Override
    public boolean onItemLongClick(View view, int position) {
        return false;
    }

    @OnClick({R.id.back_iv, R.id.confirm})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.back_iv:
//                setResult(RESULT_CANCELED);
                finish();
                break;
            case R.id.confirm:
                submitData();
                break;
        }
    }

    public void setBackground(){
        confirm.setEnabled(true);
        confirm.setBackgroundResource(R.drawable.btn_main_new_darkgreen);
    }

    private void getReasonList(){
        RequestOptService.getEndDealPage(this, new Response.Listener<NetBeanWrapper<StartDealRespBean>>() {
            @Override
            public void onResponse(NetBeanWrapper<StartDealRespBean> response) {
                if(handleResponse(response)){
                    return;
                }

                reasonList = response.getModelData().getCauseList();
                reasonAdapter.setList(reasonList);
                reasonAdapter.notifyDataSetChanged();
            }
        },getDefaultErrorListener());
    }
    /**
     * 提交数据请求
     */
    private void submitData() {
        String reason = reasonAdapter.getReasonText();
        String inputText = inputReasonEdit.getText().toString();
        if (CheckLogicUtil.isEmpty(reason) && CheckLogicUtil.isEmpty(inputText)) {
            DialogUtil.ToastMessage(this, R.string.end_deal_with_problems_hint);
            return;
        }/*else if(reason.equals("其他原因") && CheckLogicUtil.isEmpty(inputText)){
            DialogUtil.ToastMessage(this, R.string.end_deal_with_problems_hint);
            return;
        } */else if(reasonAdapter.getCheckPosition() == reasonList.size() - 1
                && CheckLogicUtil.isEmpty(inputText)){
            DialogUtil.ToastMessage(this, R.string.end_deal_with_problems_hint);
            return;
        }

        getProgressDialog().show();
        List<CarPhotoBean> carPhotoBeanList = uploadImgAdapter.getCameraList();

        String imageUrls = "";
        StringBuffer stringBuffer = new StringBuffer(imageUrls);
        for (int i = 0; i < carPhotoBeanList.size(); i++) {
            if (i == 0) {
                stringBuffer.append(carPhotoBeanList.get(i).getUrl());
            } else {
                stringBuffer.append(",").append(carPhotoBeanList.get(i).getUrl());
            }
        }
        imageUrls = stringBuffer.toString();
        endDeal(carId,reason,inputText,location.getLatitude(),location.getLongitude(),imageUrls);
    }

    @Override
    public void onClickTakePhoto() {
        File file = new File(getExternalCacheDir(), System.currentTimeMillis() + ".jpg");
        takePhoto(file);
    }

    @Override
    public void selectPhotoFromGallery() {
        chosePhotoFromGallery();
    }

    public void endDeal(int carId,String cause,String detail,double lat,double lng,String imgUrls){
        RequestOptService.endDeal(getApplicationContext(), carId, cause, detail, lat, lng, imgUrls, new Response.Listener<NetBaseWrapper>() {
            @Override
            public void onResponse(NetBaseWrapper response) {
                getProgressDialog().dismiss();
                if(!handleResponse(response)){
                    DialogUtil.ToastMessage(EndDealWithProblemsActivity.this,"操作成功");
                    Intent intent = new Intent(EndDealWithProblemsActivity.this,NormalHomeActivity.class);
                    intent.setAction(com.fqcar.fqdf.util.Constants.Action.HOME_REFRESH_ACTION);
                    startActivity(intent);
                }
            }
        },getDefaultErrorListener());
    }
    private void uploadImage(final String filePath, final int updatePosition) {
        if (FileUtil.isExists(filePath)) {

            final String uploadName = "fqdf/carImage/" + carId + "/" + System.currentTimeMillis() + ".jpg";
            final String uploadUrl = DFApp.OSSBaseUrl + uploadName;
            PutObjectRequest putObjectRequest = new PutObjectRequest(DFApp.bucketName, uploadName, filePath);
            putObjectRequest.setProgressCallback(new OSSProgressCallback<PutObjectRequest>() {
                @Override
                public void onProgress(PutObjectRequest putObjectRequest, long l, long l1) {

                }
            });

            OSSAsyncTask asyncTask = DFApp.getOss().asyncPutObject(putObjectRequest, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
                @Override
                public void onSuccess(PutObjectRequest putObjectRequest, PutObjectResult putObjectResult) {

                    getUploadImgProgressDialog().dismiss();
                    EndDealWithProblemsActivity.this.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            uploadImgAdapter.updateItem(updatePosition, uploadUrl);
                            uploadImgAdapter.notifyDataSetChanged();
                        }
                    });

                }

                @Override
                public void onFailure(PutObjectRequest putObjectRequest, ClientException e, ServiceException e1) {
                    getUploadImgProgressDialog().dismiss();
                    DialogUtil.ToastMessage(EndDealWithProblemsActivity.this, "上传失败!");
                }
            });

        }
    }
}
